package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.fragment.ChooseFriendDialogFragment.OnChooseFriendDialogFragment;
import com.nullpointer.xchatfinal.object.SelectFriend;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBGroupChatManager;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.core.QBEntityCallbackImpl;

public class CreatePrivateGroupDialogFragment extends DialogFragment {
	private static final String MEMBER_USER = "MEMBER_USER";
	private EditText etName;
	private TextView tvMember;
	private LinearLayout llMember;
	private Button btCreate;
	private Button btCancel;
	private List<String> userIDs = new ArrayList<String>();
	private List<String> userNames = new ArrayList<String>();
	private OnCreatePrivateGroupDialogFragment listener;

	public static CreatePrivateGroupDialogFragment newInstance(
			List<SelectFriend> memberUser) {
		CreatePrivateGroupDialogFragment f = new CreatePrivateGroupDialogFragment();
		Bundle args = new Bundle();
		if (memberUser == null) {
			args.putString(MEMBER_USER, null);
		} else {
			args.putString(MEMBER_USER, SelectFriend.toJsonArray(memberUser));
		}
		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String json = getArguments().getString(MEMBER_USER);
		if (json != null) {
			List<SelectFriend> users = new ArrayList<SelectFriend>();
			users.addAll(SelectFriend.fromJsonArrayToSelectFriends(json));
			for (SelectFriend user : users) {
				userIDs.add(user.getUserID());
				userNames.add(user.getUserName());
			}
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_create_private_group,
				container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (userIDs.size() > 0) {
			etName.setText(TextUtils.join(", ", userNames));
			tvMember.setText(TextUtils.join(", ", userNames));
		} else {
			showInfo("Name must > 3 char", false);
		}
	}

	private void setEvent() {
		llMember.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					final ChooseFriendDialogFragment dialog = ChooseFriendDialogFragment
							.newInstance(null, new ArrayList<>(userIDs));
					dialog.setOnChooseFriendDialogFragment(new OnChooseFriendDialogFragment() {

						@Override
						public void onChooseFriend(
								final List<SelectFriend> users) {
							userIDs.clear();
							userNames.clear();
							if (users.size() == 0) {
								return;
							}
							KiraGameLog.d("list choose friend " + users);

							for (SelectFriend user : users) {
								userIDs.add(user.getUserID());
								userNames.add(user.getUserName());
							}
							tvMember.setText(TextUtils.join(", ", userNames));
						}

						@Override
						public void onCancel() {

						}
					});
					FragmentTransaction transaction = getActivity()
							.getSupportFragmentManager().beginTransaction();
					transaction.add(dialog, "ChooseFriendDialogFragment");
					transaction.commitAllowingStateLoss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		btCreate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(getActivity(), etName);
				createGroup();
			}
		});

		btCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});

		etName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etName.getText() != null
						&& etName.getText().toString().trim().length() >= 3) {
					if (Utils.checkBadword(etName.getText().toString())) {
						btCreate.setText("Don't use sexual content!");
						showInfo("Don't use sexual content!", false);
					} else {
						hideInfo();
					}
				} else {
					showInfo("Name must > 3 char", false);
				}
			}
		});
	}

	private void showInfo(String info, boolean isClickable) {
		btCreate.setText(info);
		btCreate.setEnabled(isClickable);
		btCancel.setVisibility(View.GONE);
	}

	private void hideInfo() {
		btCreate.setText("Create");
		btCreate.setEnabled(true);
		btCancel.setVisibility(View.VISIBLE);
	}

	protected void createGroup() {
		showInfo("Creating group...", false);
		ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
		occupantIdsList.add(DataManager.getInstance(getActivity())
				.getCurrentUser().getUserID());

		QBDialog dialog = new QBDialog();
		dialog.setName(etName.getText().toString());
		// dialog.setPhoto("1786");

		dialog.setType(QBDialogType.GROUP);
		for (String id : userIDs) {
			occupantIdsList.add(Integer.parseInt(id));
		}

		dialog.setOccupantsIds(occupantIdsList);

		QBGroupChatManager groupChatManager = QBChatService.getInstance()
				.getGroupChatManager();
		groupChatManager.createDialog(dialog,
				new QBEntityCallbackImpl<QBDialog>() {
					@Override
					public void onSuccess(QBDialog mDialog, Bundle args) {
						if (listener != null) {
							listener.onCreated(mDialog);
						}
						hideInfo();
						dismiss();
					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("createGroup errors " + errors);
						showInfo("Try again!", true);
					}
				});
	}

	private void findViewIds(View view) {
		etName = (EditText) view.findViewById(R.id.et_name);
		tvMember = (TextView) view.findViewById(R.id.tv_member);
		llMember = (LinearLayout) view.findViewById(R.id.ll_member);
		btCreate = (Button) view.findViewById(R.id.bt_create);
		btCancel = (Button) view.findViewById(R.id.bt_cancel);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		Utils.hideKeyboard(getActivity(), etName);
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		super.onCancel(dialog);
		Utils.hideKeyboard(getActivity(), etName);
	}

	// protected void showChooseImageFragment() {
	// final ChooseImageDialogFragment dialog = new ChooseImageDialogFragment();
	// dialog.setOnChooseImageDialogFragment(new OnChooseImageDialogFragment() {
	//
	// @Override
	// public void onGallery() {
	// selectImageFromGallery();
	// }
	//
	// @Override
	// public void onCamera() {
	// selectImageFromCamera();
	// }
	// });
	// FragmentTransaction transaction = getActivity()
	// .getSupportFragmentManager().beginTransaction();
	// transaction.add(dialog, "ChooseImageDialogFragmentEditProfile");
	// transaction.commitAllowingStateLoss();
	// }
	//
	// protected void selectImageFromGallery() {
	// Intent intent = new Intent(getActivity(), ProcessImage.class);
	// intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, false);
	// intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
	// intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
	// startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
	// }
	//
	// protected void selectImageFromCamera() {
	// Intent intent = new Intent(getActivity(), ProcessImage.class);
	// intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, true);
	// intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
	// intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
	// startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
	// }

	public void setOnCreatePrivateGroupDialogFragment(
			OnCreatePrivateGroupDialogFragment listener) {
		this.listener = listener;
	}

	public interface OnCreatePrivateGroupDialogFragment {
		public void onCreated(QBDialog mDialog);
	}
}
